package com.bsoft.gol.hcs.visitrecord.dao;

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.atag.dao.ext.HibernateExtendDAO;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import com.bsoft.gol.hcs.utils.CommonUtils;
import org.atag.dao.action.QoHibernateStatelessResultAction;
import org.atag.dao.model.SimplePageInfo;
import com.bsoft.gol.hcs.visitrecord.bean.qo.HospitalVisitsRecordListQo;
import com.bsoft.gol.hcs.visitrecord.bean.vo.HospitalVisitsRecordListVo;
import com.bsoft.gol.hcs.visitrecord.entity.VrDispensingRecord;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by ChenJij on 2020/9/4.
 */
public abstract class VrDispensingRecordDAO extends HibernateExtendDAO<VrDispensingRecord> {
    public VrDispensingRecordDAO() {
        this.setKeyField("distributionId");
    }

    /**
     * @description: 更新满意度调查已完成数量
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/10/9 13:25
     */
    @DAOMethod(sql = "update VrDispensingRecord set finishNumber=finishNumber+1 where  distributionId=:businessId")
    public abstract void updateFinishNumber(@DAOParam("businessId") String businessId);

    /**
     * 查询所有的病人id
     *
     * @return java.util.List<java.lang.String>
     * @throws
     * @author tongtp
     * @date 2022/6/14 15:15
     */
    public List<String> queryAllPatientId(final List<String> departmentIds) {
        HibernateStatelessResultAction<List<String>> action =
                new AbstractHibernateStatelessResultAction<List<String>>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        StringBuilder sqlBuilder = new StringBuilder();
                        sqlBuilder.append("SELECT DISTINCT patient_id AS patientId ");
                        sqlBuilder.append(" FROM vr_dispensing_record ");
                        sqlBuilder.append(" WHERE patient_id is not null ");
                        if (CommonUtils.isNotEmpty(departmentIds)) {
                            sqlBuilder.append(" and department_id in (:departmentIds) ");
                        }
                        Query query = ss.createSQLQuery(sqlBuilder.toString());
                        if (CommonUtils.isNotEmpty(departmentIds)) {
                            query.setParameterList("departmentIds", departmentIds);
                        }
                        List list = query.list();
                        List<String> voList;
                        if (CommonUtils.isNotEmpty(list)) {
                            voList = list;
                        } else {
                            voList = new ArrayList<>();
                        }
                        setResult(voList);
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 根据患者id获取最新的一条数据
     */
    public VrDispensingRecord getPatientIdAndLastOne(String patientId, String departmentId) {

        HibernateStatelessResultAction<VrDispensingRecord> action =
                new AbstractHibernateStatelessResultAction<VrDispensingRecord>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        List departmentIds = null;
                        if (CommonUtils.isNotNull(departmentId)) {
                            departmentIds = Arrays.asList(departmentId.split(","));
                        }
                        StringBuilder builder = new StringBuilder();
                        builder.append(" from VrDispensingRecord  where  patientId =:patientId ");
                        builder.append(" and dispensingDate is not null");
                        if (CommonUtils.isNotEmpty(departmentIds)) {
                            builder.append(" and departmentId in (:departmentIds) ");
                        }
                        builder.append(" order by dispensingDate desc");
                        Query query = ss.createQuery(builder.toString());
                        query.setParameter("patientId", patientId);
                        if (CommonUtils.isNotEmpty(departmentIds)) {
                            query.setParameterList("departmentIds", departmentIds);
                        }
                        // 查询的条数
                        query.setMaxResults(1);
                        // 开始查询的位置
                        query.setFirstResult(0);
                        List<Map<String, Object>> dbList = query.list();
                        if (CommonUtils.isNotEmpty(dbList)) {
                            setResult(ConversionUtils.convert(dbList.get(0), VrDispensingRecord.class));
                        } else {
                            setResult(null);
                        }
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    @DAOMethod(sql = " from VrDispensingRecord where clinicDistributionId =:clinicDistributionId and organizationId=:organizationId")
    public abstract VrDispensingRecord getVrDispensingRecord(@DAOParam("clinicDistributionId") String clinicDistributionId, @DAOParam("organizationId") String organizationId);

    public SimplePageInfo<HospitalVisitsRecordListVo> queryOutpatientVisitRecordList(HospitalVisitsRecordListQo qo){
        QoHibernateStatelessResultAction<HospitalVisitsRecordListVo, HospitalVisitsRecordListQo> action = new QoHibernateStatelessResultAction(true, qo, HospitalVisitsRecordListVo.class);
        action.setSql(" SELECT {{" +
                " '6' businessType, " +
                " distribution_id AS businessId, " +
                " organization_id AS organizationId, " +
                " patient_id AS patientId, " +
                " patient_name AS patientName, " +
                " patient_sex AS patientSex, " +
                " patient_age_text AS patientAge, " +
                " department_name AS departmentName, " +
                " survey_number AS surveyNumber, " +
                " finish_number AS finishNumber, " +
                " patient_medical_card_number AS patientMedicalCardNumber, " +
                " patient_medical_card_type AS patientMedicalCardType, " +
                " card_number AS cardNumber, " +
                " card_type AS cardType, " +
                " telephone, " +
                " pharmacy_name AS pharmacyName, " +
                " doctor_name AS doctorName, " +
                " dispensing_date AS dispensingDate }}" +
                "FROM " +
                " vr_dispensing_record where 1=1 ");
        action.addCondition(" and patient_name =:patientName ");
        action.addCondition(" and telephone =:telephone ");
        action.addCondition(" and patient_medical_card_number =:patientMedicalCardNumber ");
        action.addCondition(" and organization_id =:organizationId ");
        action.addCondition(" and department_id =:departmentId ");
        action.addCondition(" and doctor_id =:doctorId ");
        action.addCondition(" and dispensing_date >=:beginDate ");
        action.addCondition(" and dispensing_date <:endDate ");
        action.addCondition(" and pharmacy_code =:pharmacyCode ");

        HibernateSessionTemplate.instance().execute(action);
        SimplePageInfo<HospitalVisitsRecordListVo> pageInfo = action.getSimpleResultPage();
        return pageInfo;
    }
}